package com.example.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.system.entity.PathKey;
import com.example.system.mapper.PathKeyMapper;
import com.example.system.service.IPathKeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Random;

@Service
public class PathKeyServiceImpl extends ServiceImpl<PathKeyMapper, PathKey> implements IPathKeyService {
    @Autowired
    PathKeyMapper pathKeyMapper;

    public String getRandomPathKey() {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取当天0点的LocalDateTime
        LocalDateTime startOfToday = today.atStartOfDay();
        System.out.println("今天0点: " + startOfToday);
        // 获取第二天0点的LocalDateTime
        LocalDateTime startOfTomorrow = today.plusDays(1).atStartOfDay();
        System.out.println("明天0点: " + startOfTomorrow);
        if (pathKeyMapper.existsByStartTimeAndEndTime(startOfToday, startOfTomorrow)) {
            return pathKeyMapper.findRandomPathKeyByStartTimeAndEndTime(startOfToday, startOfTomorrow);
        } else {
            Random random = new Random();
            StringBuilder stringBuilder = new StringBuilder(10);
            String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-+*";
            for (int i = 0; i < 10; i++) {
                int index = random.nextInt(characters.length());
                stringBuilder.append(characters.charAt(index));
            }
            String newPathKey = stringBuilder.toString();
            PathKey pathKey = new PathKey();
            pathKey.setRandomPathKey(newPathKey);
            pathKey.setSetTime(startOfToday);
            pathKeyMapper.addByPathKey(pathKey);
            return newPathKey;
        }
    }
}
